<?php

namespace App\Http\Controllers\Admin;

use App\Models\Area;
use App\Models\User;
use App\Models\XcDevice;
use App\Models\XcFactoryWashMode;
use App\Models\XcRenter;
use App\Models\XcSite;
use App\Models\XcSiteOrder;
use App\Models\XcUserRecharge;
use App\Models\XcUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Api\WechatController;
use Illuminate\Support\Facades\Log;


/***
 * 站点订单控制层
 *
 */
class SiteOrderController extends Controller
{
	/**
     * 站点订单列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function index(Request $request)
    {
        $citycode  	= $request->get("citycode","420100");

        $crole_name = Auth::user()->roles()->get()->toArray()??"";
        if ($crole_name[0]['name'] == "root"){
            $citys 	= GetCitys();
            $site = XcSite::query();
        }else{
            $citys 	= GetCitys($citycode);
            $site = XcSite::where("city_code", $citycode);
        }
        $site = $site->pluck("name", "id")->toArray();
        return View::make('admin.siteorder.index',compact('citys', 'citycode', 'site'));
    }

    /**
     * 获得站点订单数据，分页信息
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $citycode  = $request->get("citycode","420100");
        $site_id   = $request->get("site_id",0);
        $order_sn  = $request->get("order_sn","");
        $starttime = $request->get("starttime","");
        $endtime   = $request->get("endtime","");
        $status    = $request->get("status","");
        $type  	   = $request->get("type","");


		$order = XcSiteOrder::select('*');

        if ($status != '') {
            $order->where('status', $status);
        } else {
            $order->where('status', '>', -1);
        }

        if ($type != '') {
            if ($type == 0) {
                $order->where('type', 0)->where('points', '>', 0);
            } elseif ($type == 1) {
                $order->where('type', 0)->where('money', '>', 0);
            } else {
                $order->where('type', $type);
            }
        }

        if ($site_id > 0) {
            $order->where("site_id", $site_id);
        }
        if (!empty($order_sn)) {
            $xcuser = XcUser::where('mobile', $order_sn)->first();
            $order->where(function ($query) use ($order_sn, $xcuser) {
                $query->Where('order_sn', '=', $order_sn);
                if (!empty($xcuser) && !empty($xcuser->mobile)) {
                    $query->orWhere('openid', '=', $xcuser->openid);
                }
            });
        }

        if (!empty($starttime) && !empty($endtime)) {
            $order->whereRaw("SUBSTRING(created_at,1,10) >='" . $starttime . "' and SUBSTRING(created_at,1,10) <= '" . $endtime . "'");
        }

        $res = $order->with(["site", "user", "userrechage"])->orderby("id", "desc")->paginate($request->get('limit', 10));

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        return Response::json($data);
    }

    /**
     * 退款表单
     * 
     */ 
    public function refundform(Request $request)
    {
        $id = $request->get("id");
        $order = XcSiteOrder::where('id', '=', $id)->first()->toArray();
        $type_arra = [0 => '余额或积分',
                      2 => '年卡', 
                      3 => '季卡', 
                      4 => '月卡', 
                      5 => '次卡', 
                      6 => '即充即用'];

        return View::make('admin.siteorder.refund',compact('order','type_arra'));
    }

    /***
     * 退款操作，操作描述如下，订单表 type分如下几种情况 ：
     * 1.type == 0 时，即把相应的余额和积分返还给用户的，即修改user表money 或者 userpoints
     * 2.type == 2,3,4时，会员卡，只需要直接把当前订单状态标注成已退款即可
     * 3.type == 5 时，次卡，需要返还到次卡表里，即即xc_user_recharge表used_fine_washing_num或used_fast_washing_num减1
     * 4.type == 6时，即充即用，
     *        分两种情况：A.订单未使用时，不仅要把钱退到用户微信里面，还要把订单标注成已退款，用户表xuser表余额减去相应金额
     *                  B.订单已使用(可能机器问题造成洗车过程不完整)，只需要退给用户微信，标注订单为已退款。
     * 
     */ 
    public function refund(Request $request)
    {
        
        $user       = Auth::guard('web')->user();
        $id         = $request->post("id");
        $order_sn   = $request->post("order_sn");
        $remarks    = $request->post("remarks");

        $order      = XcSiteOrder::where([["order_sn",'=', $order_sn]])->first();
        $remarks    ='['.date("Y-m-d H:i:s").']:用户-'.$user->name.',user id-'.$user->id.' 处理退款,备注-'.$remarks.'\n';
        if (!empty($order->remarks)) $remarks = $order->remarks.'\n'.$remarks;

         DB::beginTransaction();
        try{
            //如果是从余额和积分扣除的，则直接返还到余额和积分即可
            if ($order->type == 0) {
            

            //如果是年卡、季卡、月卡，则直接修改状态即可，标注成已退款状态即可
            }else if (in_array($order->type,[2,3,4])){


            //如果是次卡，则需要把次卡次数返还到次卡的表里，即xc_user_recharge表used_fine_washing_num或used_fast_washing_num减1
            }else if ($order->type == 5){

            }else if ($order->type == 6){
                //获得充值的订单信息
                $userrecharge=XcUserRecharge::where([["site_order_sn", '=',$order_sn],['pay_status','=',2]])->first();
                if (empty($userrecharge)) {
                    return '<script>window.parent.layer.msg("用户未完成充值,不能退款");</script>';
                }

                //如果未使用要退的情况，需要判断余额是否够扣
                $xcuser = XcUser::where('openid', $order->openid)->first();
                if ($order->status == 0){
                    if ($xcuser->money < $order->money){
                        return '<script>window.parent.layer.msg("余额不够退款,请检查");</script>';
                    }
                }
                

                $refund_no = OrderSN("RF");
                $wechat = new WechatController();
                $re = $wechat->refund($userrecharge->order_sn,$refund_no,$order->money,'系统退款');
                Log::info("微信接口退款返回信息：");
                Log::info($re);
                if ($re['result_code'] == 'SUCCESS'){

                    $str  = $this->UpdateSiteOrderRecharge($order, $xcuser, $user , $re, $remarks);
                    
                }else{
                    if($re['err_code_des'] == '订单已全额退款'){
                        $str  = $this->UpdateSiteOrderRecharge($order, $xcuser, $user , $re, $remarks);
                        
                    }else{
                         $str = '<script>window.parent.layer.closeAll();
                        window.parent.layer.msg("退款失败");
                        window.parent.layui.table.reload("dataTable");</script>';
                    }
                }
                DB::commit();
                return $str;
                
               
            }
            //return Redirect::to(URL::route('admin.site',['id' => $data['renter_id']]))->with(['success'=>'创建成功']);
            
        }catch (\Exception $exception){
            DB::rollback();
            return response()->json(['code' => -1,'msg' => $exception->getMessage()]);
        }
    }

    /**
     * 即充即用，退款需要更新的几张表：xc_site_order, xc_user_recharge, xc_user 表
     * 
     */ 
    private function UpdateSiteOrderRecharge($order, $xcuser, $user , $re, $remarks)
    {
        $order_sn = $order->order_sn;
        //更新几个表的状态为已退款状态
        $flag = XcSiteOrder::where('order_sn', $order_sn)
                    ->update(['status' => 2, 'remarks' => $remarks]);
        $flagc = XcUserRecharge::where('site_order_sn', $order_sn)
                    ->update([
                                'pay_status'    => 3,
                                'status'        => 4,
                                'refund_id'     => $re['refund_id']??0,
                                'refund_no'     => $re['out_refund_no']??"",
                                'refund_time'   => date('Y-m-d H:m:s'),
                                'suggest_refund_amount' => $order->money,
                                'refund_amount' => $order->money,
                                'refund_worker' => $user->nickname,
                                'refund_remark' => $remarks
                            ]);
        if ($order->status == 0)  $uflag = $xcuser->update(['money' => DB::raw('money - '.$order->money)]);
        Log::info("更新退款状态：");
        Log::info('update xc_site_order status:'.$flag.',update xu_user_recharge status:'.$flagc);

        return '<script>window.parent.layer.closeAll();
                        window.parent.layer.msg("退款成功");
                        window.parent.layui.table.reload("dataTable");</script>';
    }
}